import {Component, ViewChild} from '@angular/core';
import {NgForm} from "@angular/forms";
import {FormField, FormFieldType} from "../common/constant";
import {Step, Step1} from "../store/models/step.model";

@Component({
  selector: 'app-step1',
  templateUrl: './step1.component.html',
  styleUrls: ['./step1.component.less']
})
export class Step1Component {
  @ViewChild('myForm', {static: true}) myForm: NgForm | undefined;

  constructor() {
  }

  formFields: FormField[] = [
    {
      name: 'name', label: '你的名字', type: 'text',
      required: true,
      minlength: '3',
      error: [{
        type: 'minlength',
        message: '小于最小长度'
      }, {
        type: 'required',
        message: '必填'
      }]
    },
    {
      name: 'isMale',
      label: '你是男生吗？',
      type: 'radio',
      radioData: [{label: 'Yes', value: 'Y'}, {label: 'No', value: 'N'}],
      radioLayout: 'row'
    },
    {
      name: 'isHandsome',
      label: '你帅吗？',
      type: 'radio',
      radioData: [{label: 'Yes', value: 'Y'}, {label: 'No', value: 'N'}],
      radioLayout: 'col'
    },
    {name: 'handsomeReason', label: '描述下原因', type: 'custom'},
  ];

  ngOnInit() {

  }

  public checkStep1Data() {
    let myForm = this.myForm
    if (myForm?.form.valid) {
     return true
    } else {
      this.updateFormStatus()
    }
    return false
  }
  getStep1Data() : {data: Step1}
  {
    return {
      data: {...this.myForm?.form.value} as Step1,
    }
  }

  updateFormStatus() {
    let myForm = this.myForm
    if(!myForm) return
    Object.values(myForm.form.controls).forEach(control => {
      if (control.invalid) {
        control.markAsDirty();
        control.updateValueAndValidity({onlySelf: true});
      }
    });
  }

  onSubmit(myForm: NgForm) {
    if (myForm.form.valid) {
      console.log({
        data: {...this.myForm?.form.value},
        step: 1
      })
    } else {
      this.updateFormStatus()
    }
  }

  isFormFieldOfType<T extends FormFieldType>(field: FormField, type: T): field is Extract<FormField, { type: T }> {
    return field.type === type;
  }
}
